package com.xjj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjj.common.R;
import com.xjj.dto.DishDto;
import com.xjj.entity.Category;
import com.xjj.entity.Dish;
import com.xjj.service.CategoryService;
import com.xjj.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 分页获取数据
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){

        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(name != null,Dish::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(pageInfo,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 查询详情
     * @param
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> queryDish(@PathVariable Long id){
        log.info("查询详情====>"+id);
        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return R.success(dishDto);
    }

    /**
     * 获取菜品列表，套餐管理添加套餐调用
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    public R<List<Dish>> Dishlist(Long categoryId){
        String key="dish_"+categoryId;

        List<Dish> list= (List<Dish>) redisTemplate.opsForValue().get(key);

        if (list!=null){
            return R.success(list);
        }
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,categoryId);
        list = dishService.list(dishLambdaQueryWrapper);

        redisTemplate.opsForValue().set(key,list,60, TimeUnit.MINUTES);

        return R.success(list);
    }
    /**
     * 停售，起售
     * @param
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> status (@PathVariable("status") Integer status,@RequestParam List<Long> id){
        log.info("停售起售====>"+ id);
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.in(id!=null,Dish::getId,id);
        List<Dish> list = dishService.list(dishLambdaQueryWrapper);
        for (Dish dish:list){
            if (dish!=null){
                dish.setStatus(status);
                dishService.updateById(dish);
            }
        }

        String key="dish_"+id;
        redisTemplate.delete(key);


        return R.success("更改销售状态成功!");
    }

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info("新增菜品===>{}",dishDto);
        dishService.saveWithFlavor(dishDto);
        String key="dish_"+dishDto.getCategoryId();
        redisTemplate.delete(key);

        return R.success("添加菜品成功！");
    }

    /**
     * 删除菜品
     */
    @DeleteMapping
    public R<String> delete(Long[] id){
        log.info("删除菜品===>{}",id);
        dishService.removeWithFlavor(id);

        String key="dish_"+id;
        redisTemplate.delete(key);


        return R.success("删除菜品成功！");
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);

        String key="dish_"+dishDto.getCategoryId();
        redisTemplate.delete(key);


        return R.success("修改菜品成功！");
    }
}
